import { Application } from "egg";

export default (app: Application) => {
  const { STRING, INTEGER, DATE, ENUM, TEXT, DECIMAL } = app.Sequelize;

  const Project = app.model.define(
    "Project",
    {
      id: {
        type: INTEGER,
        primaryKey: true,
        autoIncrement: true,
      },
      title: {
        type: STRING(200),
        allowNull: false,
        comment: "项目标题",
      },
      description: {
        type: TEXT,
        allowNull: false,
        comment: "项目描述",
      },
      content: {
        type: TEXT,
        allowNull: true,
        comment: "项目详细内容",
      },
      category: {
        type: ENUM("education", "medical", "disaster", "environment", "other"),
        allowNull: false,
        comment: "项目分类",
      },
      targetAmount: {
        type: DECIMAL(20, 2),
        allowNull: false,
        comment: "目标金额",
      },
      currentAmount: {
        type: DECIMAL(20, 2),
        defaultValue: 0,
        comment: "当前已筹金额",
      },
      status: {
        type: ENUM(
          "draft",
          "pending",
          "approved",
          "rejected",
          "funding",
          "completed",
          "cancelled"
        ),
        defaultValue: "draft",
        comment: "项目状态",
      },
      images: {
        type: TEXT,
        allowNull: true,
        comment: "项目图片，JSON格式",
      },
      documents: {
        type: TEXT,
        allowNull: true,
        comment: "项目文档，JSON格式",
      },
      startDate: {
        type: DATE,
        allowNull: true,
        comment: "项目开始时间",
      },
      endDate: {
        type: DATE,
        allowNull: true,
        comment: "项目结束时间",
      },
      creatorId: {
        type: INTEGER,
        allowNull: false,
        comment: "创建者ID",
      },
      contractAddress: {
        type: STRING(100),
        allowNull: true,
        comment: "智能合约地址",
      },
      blockchainTxHash: {
        type: STRING(100),
        allowNull: true,
        comment: "区块链交易哈希",
      },
      approvedAt: {
        type: DATE,
        allowNull: true,
        comment: "审核通过时间",
      },
      approvedBy: {
        type: INTEGER,
        allowNull: true,
        comment: "审核人ID",
      },
      rejectReason: {
        type: TEXT,
        allowNull: true,
        comment: "拒绝原因",
      },
    },
    {
      tableName: "projects",
      timestamps: true,
      paranoid: true,
      underscored: true,
    }
  );

  // 关联关系
  Project.associate = function (): void {
    // 项目属于一个创建者
    app.model.Project.belongsTo(app.model.User, {
      foreignKey: "creatorId",
      as: "creator",
    });

    // 项目可以有多个捐款记录
    app.model.Project.hasMany(app.model.Donation, {
      foreignKey: "projectId",
      as: "donations",
    });

    // 项目可以有多个进展报告
    app.model.Project.hasMany(app.model.ProjectUpdate, {
      foreignKey: "projectId",
      as: "updates",
    });
  };

  return Project;
};
